package com.hailiao.hailiao_sdk.activity;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.hailiao.hailiao_sdk.R;
import com.hailiao.hailiaolibrary.Util.HailiaoMessageUtil;
import com.hailiao.hailiaolibrary.hailiaoInterface.HlMessageReceiveInterface;
import com.hailiao.hailiaolibrary.hailiaoInterface.HlSendMessageInterface;
import com.hailiao.hailiaosdk.MainApp;
import com.hailiao.hailiaosdk.beidou.HailiaoManager;
import com.hailiao.hailiaosdk.constant.MsgType;
import com.hailiao.hailiaosdk.dto.CardGlzkDto;
import com.hailiao.hailiaosdk.dto.CardLocationDto;
import com.hailiao.hailiaosdk.dto.CardMessageDto;
import com.hailiao.hailiaosdk.dto.GpsSatelliteDto;
import com.hailiao.hailiaosdk.dto.LoginReceiptDto;
import com.hailiao.hailiaosdk.dto.SendMsgResult;
import com.hailiao.hailiaosdk.dto.TobuluLogicDto;
import com.hailiao.hailiaosdk.dto.TrailCacheDto;
import com.hailiao.hailiaosdk.dto.TrailCatalogDto;
import com.hailiao.hailiaosdk.entity.UserMessage;
import com.hailiao.hailiaosdk.hailiaoListner.HlBindCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlClearTrailCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlConnectCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlDisconnectCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetBeidouTimeCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetCardInfoCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetLoactionUploadParamsCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetLocationCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetMachineInfoCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetTrailCacheCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetTrailCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetTrailCatalogCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlGetVersionCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlOnCustomMsgReceive;
import com.hailiao.hailiaosdk.hailiaoListner.HlOnMsgReceive;
import com.hailiao.hailiaosdk.hailiaoListner.HlRdStatusCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlSendMessageCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlSetLocationUploadParamsCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlSetSoundSwitchCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlSetTrailParamsCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlSetUserIdCallBack;
import com.hailiao.hailiaosdk.hailiaoListner.HlStartLocationUploadCallback;
import com.hailiao.hailiaosdk.hailiaoListner.HlStopLocationUploadCallback;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    HailiaoManager hailiaoManager = HailiaoManager.getHailiaoManager();
    //发送短报文要调用的地址
    private final static String sendBdMessageUrl = "http://api.hellobeidou.com/api/msg/send";
    //查询最新接收消息要调用的地址
    private final static String checkBdMessageUrl = "http://api.hellobeidou.com/api/msg/list/receive";
    private HlOnMsgReceive hlOnMsgReceive = new HlOnMsgReceive() {
        @Override
        public void onMsgReceived(UserMessage userMessage) {
            Log.e("接收短报文：", userMessage.getContent());
            Log.e("接收短报文：", userMessage.getMsgType().toString());
            Log.e("接收短报文：", String.valueOf(userMessage.getLatitude()));
            Log.e("接收短报文：", String.valueOf(userMessage.getLongitude()));
            Log.e("接收短报文：", userMessage.getSendLocation());
        }

        @Override
        public void onTobuluLogicReceived(TobuluLogicDto tobuluLogicDto) {
            Log.e("接收Logic：", tobuluLogicDto.getMsgType().toString());
            Log.e("接收Logic：", tobuluLogicDto.getContentHexStr());
        }
    };

    private HlOnCustomMsgReceive hlOnCustomMsgReceive = new HlOnCustomMsgReceive() {
        @Override
        public void onBeidouMsgReceive(CardMessageDto cardMessageDto) {
            Log.e("接收自定义短报文", cardMessageDto.getContent());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MainApp.init(this, "6a518c6be8e0dddc");//将6a518c6be8e0dddc替换为您的appkey
        hailiaoManager.setHlOnMsgReceive(hlOnMsgReceive);//设置短报文接收监听
        //hailiaoManager.setHlOnCustomMsgReceive(hlOnCustomMsgReceive);
        /**
         * 初始化
         * 第一个参数为分配的appId
         * 第二个参数为分配的appSecret
         * 第三个参数为发送短报文要调用的url
         * 第四个参数为接收短报文要调用的url
         */
        HailiaoMessageUtil.initHailiaoMessageUtil("bd1ae86b4c356a5c84", "b90b11651ae86b4c356a5c84852493d4",
                sendBdMessageUrl, checkBdMessageUrl);


        FloatingActionButton fabReceive = (FloatingActionButton) findViewById(R.id.fab_msg_receive);
        FloatingActionButton fabSend = (FloatingActionButton) findViewById(R.id.fab_msg_send);
        FloatingActionButton fab3 = (FloatingActionButton) findViewById(R.id.fab_3);
        FloatingActionButton fab4 = (FloatingActionButton) findViewById(R.id.fab_4);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });
        fabSend.setOnClickListener(this);
        fabReceive.setOnClickListener(this);
        fab3.setOnClickListener(this);
        fab4.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fab_msg_send:
                //hl242216 CD:45:71:ED:E4:57   242363 F1:AB:55:BA:4A:65  007 E1:02:58:A3:28:B0  0242265 00:0E:0B:11:70:CE
                //HL105 FF:BC:E5:89:B1:92      0242404 CA:35:67:68:27:41  HLH3_0002 DE:EA:FC:F0:5A:2C
               hailiaoManager.connectBle("DE:EA:FC:F0:5A:2C", "", "", new HlConnectCallBack() {
                   @Override
                   public void onConnectSuccess(String string) {
                       Log.e("连接成功：", string);
                       getVersion();
                   }

                   @Override
                   public void onDisconnect(String s) {
                       Log.e("断开：", s);
                   }

                   //
                   @Override
                   public void onFailed(String string) {

                       Log.e("连接失败：", string);

                   }
               });

//                if (isOpenNetwork(this)) {
//                    HailiaoMessageUtil.getInstance().sendBdMessage("b2e1c70f", "237466", "1", "123ADC你好", hlSendMessageInterface);
//                    //HailiaoMessageUtil.getInstance().sendChangeSOSRequest("13828498249", "a", "b", "c", "13828498249", "13828498249",
////                    "13828498249", hlSendMessageInterface);
//                }else {
//                    Toast.makeText(this, "请先开启网络", Toast.LENGTH_SHORT).show();
//                }
                break;
            case R.id.fab_msg_receive:
//                getTrailCache();
//                getMachineInfo();
//                rdStatus(true, true);
//                sendCustomMsg();
//                disconnect();
                sendMsg();
//                register();
//                bindByNet();
//                bindByBeidou();
//                setLocationUpload(60);
//                getVersion();
//                getCardInfo();
//                HailiaoMessageUtil.getInstance().roundCheckMessage("237466", "0", 5000, hlMessageReceiveInterface);

                break;
            case R.id.fab_3:
//                getTime();
                getLocation(0);
//                sendTobuluLogic();
//                setTrailParams(10, false);
//                sendMsg();
//                setSoundSwitch(true, false);
                break;
            case R.id.fab_4:
                disconnect();
                break;
        }
    }

    /**
     * 连接成功后必须进行的第一步操作，此操作不占用北斗频度
     * 读取终端版本号
     *
     */
    private void getVersion(){
        hailiaoManager.checkVersion(new HlGetVersionCallBack() {
            @Override
            public void onSuccess(String s) {
                getMachineInfo();
//                setID_H3();
                Log.e("获取版本号成功：", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("获取版本号失败：", s);
            }
        });
    }

    /**
     * 此操作不占用北斗频度
     * 连接成功后必须进行的第二步操作，查询终端自检（成功后app建议每隔三秒去查询终端自检信息，类似于心跳）
     * 此接口作用：①检查北斗硬件模块是否可正常收发；
     * 			②检查北斗信号强度是否支持正常收发，北斗信号分为波束1-10，每个波束的信号最强为4，建议至少在有一个强度为4的波束的情况下
     * 			才去发送短报文，成功率才有保障
     */
    private void getMachineInfo(){
        hailiaoManager.getMachineInfo(new HlGetMachineInfoCallBack() {

            @Override
            public void onSuccess(com.hailiao.hailiaosdk.dto.CardZdxxDto cardZdxxDto) {
                CardGlzkDto cardGlzkDto2 = cardZdxxDto.getCardGlzkDto();
                String content = "【收】" + "\n【北斗卡号】：" + cardZdxxDto.getCardNumber() + "\n【卡类型】："
                        + (cardZdxxDto.getIcType() == 1 ? "管理卡" : "用户卡") + "\n【智能卡】："
                        + (cardZdxxDto.isIcCardStatusNormal() ? "正常" : "错误") + "\n【智能卡处理】："
                        + (cardZdxxDto.isIcCardClStatusNormal() ? "正常" : "错误") + "\n【智能卡数据】："
                        + (cardZdxxDto.isIcCardDataStatusNormal() ? "正常" : "错误") + "\n【ID号】："
                        + (cardZdxxDto.isIdNumberStatusNormal() ? "正常" : "错误") + "\n【校验码】："
                        + (cardZdxxDto.isCrcStatusNormal() ? "正常" : "错误") + "\n【序列号】："
                        + (cardZdxxDto.isSerialNumberStatusNormal() ? "正常" : "错误") + "\n【天线状态】："
                        + (cardZdxxDto.isAntStatusNormal() ? "正常" : "错误") + "\n【通道状态】："
                        + (cardZdxxDto.isChannelStatuNormal() ? "正常" : "错误") + "\n【主板状态】："
                        + (cardZdxxDto.isMsiStatusNormal() ? "正常" : "错误") + "\n【抑制状态】："
                        + (cardZdxxDto.isRestrain() ? "抑制" : "非抑制") + "\n【是否静默】："
                        + (cardZdxxDto.isSilent() ? "静默（能收不能发）" : "非静默（正常可收可发）") + "\n【波束1/波束2】："
                        + cardGlzkDto2.getBs1() + "/" + cardGlzkDto2.getBs2() + "\n【波束3/波束4】："
                        + cardGlzkDto2.getBs3() + "/" + cardGlzkDto2.getBs4() + "\n【波束5/波束6】："
                        + cardGlzkDto2.getBs5() + "/" + cardGlzkDto2.getBs6();
                Log.e("获取到该终端当前绑定的手机号码：", cardZdxxDto.getDeviceId());
                Log.e("获取终端信息成功：", cardZdxxDto.getBeamStatus());
                Log.e("获取终端信息成功：", content);
                getCardInfo();
            }

            @Override
            public void onFailed(String s) {
                Log.e("获取终端信息失败：", s);

            }
        });
    }

    /**
     * 连接成功后必须进行的第三步操作，读取北斗卡号
     * 此接口作用：①北斗卡号用于和手机号码绑定，作为id唯一标识；
     * 			②北斗卡频度用于判断下次发送短报文所需的间隔--北斗短报文有频度限制，只要发送了一条，无论送达与否，都会占用一次频度，
     * 		所以建议不要滥用频度
     */
    private void getCardInfo(){
        hailiaoManager.getCardInfo(new HlGetCardInfoCallBack() {

            @Override
            public void onSuccess(com.hailiao.hailiaosdk.dto.CardInfoDto cardInfoDto) {
                Log.e("获取卡号成功：", cardInfoDto.getCardNumber());
                if (true) {
                    //您的app应该先根据卡号和手机号码判断是否绑定关系改变了，若改变了应重新绑定，重新绑定需先将终端里面绑定的手机号码清零
                    setID_H3("00000000000");
                }else {
                    //连接流程已结束，可以发送短报文消息了
                }
            }

            @Override
            public void onFailed(String s) {
                Log.e("获取卡号失败：", s);
            }
        });
    }

    /**
     * 相当于登陆，只需要绑定一次，下次连接无需绑定，但切换了用户，绑定关系变化后需要重新绑定
     * 绑定海聊终端，此方法需在ic自检、终端自检成功后，调用发送短报文、发送位置上报接口前调用，不然无法发送短报文
     * 北斗绑定会占用北斗频度，网络绑定不会占用北斗频度
     */
    private void bindByBeidou(){
        /**
         * 走卫星信号的绑定接口，此方法可用于在无网络的情况下绑定手机号码与北斗卡号，走卫星的绑定接口无需北斗卡号，终端发送短报文时会自带
         * "18122190627"  使用这张北斗卡的用户的手机号码
         * HlBindCallBack  回调接口
         */
        hailiaoManager.sendBindRequestByBeidou("18122190627", new HlBindCallBack() {
            @Override
            public void onSuccess(LoginReceiptDto bindResult) {
                Log.e("登陆成功：", bindResult.getMessage());
                setID_H3("18122190627");//后台绑定成功后，将新绑定的手机号码设置进终端里面
            }

            @Override
            public void onFailed(String description) {
                Log.e("登陆失败：", description);

            }
        });
    }

    /**
     * 相当于登陆，只需要绑定一次，下次连接无需绑定，但切换了用户，绑定关系变化后需要重新绑定
     * 绑定海聊终端，此方法需在ic自检、终端自检成功后，调用发送短报文、发送位置上报接口前调用，不然无法发送短报文
     * 北斗绑定会占用北斗频度，网络绑定不会占用北斗频度
     */
    private void bindByNet(){
        /**
         * 走网络的绑定接口，此接口是为了方便用户在有网络的情况下用网络绑定手机号码与北斗卡号
         * "18122190627"  使用这张北斗卡的用户的手机号码
         * "0242366"       这张北斗卡的卡号，由ic自检得到
         * HlBindCallBack  回调接口
         */
        HailiaoManager.getHailiaoManager().sendBindRequestByNet("18122190627", "0242366", new HlBindCallBack() {
            @Override
            public void onSuccess(LoginReceiptDto bindResult) {
                Log.e("登陆成功：", bindResult.getMessage());
                setID_H3("18122190627");//后台绑定成功后，将新绑定的手机号码设置进终端里面
            }

            @Override
            public void onFailed(String description) {

                Log.e("登陆失败：", description);
            }
        });

    }

    /**
     * 读取北斗时间
     */
    private void getTime(){
        hailiaoManager.getBeidouTime(new HlGetBeidouTimeCallBack() {
            @Override
            public void onSuccess(String s) {
                Log.e("获取北斗时间成功：", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("获取北斗时间失败：", s);
            }
        });
    }

    /**
     * 发送聊天短报文，内容不可超过31个汉字（若包含位置信息则不可超过24个汉字）
     */
    private void sendMsg(){
        Location location = new Location(LocationManager.NETWORK_PROVIDER);
        location.setLatitude(23.3333);
        location.setLongitude(23.4444);
        /**
         *MsgType.MSG_TOMOB:	消息类型
         * "18122190627"：	接收方手机号码（不可null）
         * location：	位置信息（可null）
         * "123456"     消息内容
         */
        hailiaoManager.sendBeidouMsg(MsgType.MSG_TOMOB, "18122190627", location, "123456", new HlSendMessageCallBack() {
            @Override
            public void onSendCallBack(SendMsgResult sendMsgResult) {
                Log.e("发送成功：", sendMsgResult.getSendResult());
                Log.e("发送成功：", sendMsgResult.getDescription());
            }

            @Override
            public void onWaitingForReceipt(String s) {
                Log.e("等待回执", s);
            }

            @Override
            public void onFailed(String description) {
                Log.e("发送失败：", description);

            }
        });
    }

    /**
     * 断开连接
     */
    private void disconnect(){
        hailiaoManager.disconnectBle(new HlDisconnectCallBack() {
            @Override
            public void onSuccess(String s) {
                Log.e("断开连接成功：", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("断开连接失败：", s);
            }
        });

    }

    /**
     * 发送自定义逻辑短报文，长度0-75
     */
    private void sendTobuluLogic(){
        /*hailiaoManager.sendTobuluLogicByBeidou(MsgType.DATA_LOGIC_2, "00000000000000000000", new HlTobuluLogicCallBack() {
            @Override
            public void onSendCallBack(SendMsgResult sendMsgResult) {
                Log.e("发送逻辑成功", sendMsgResult.getSendResult());
            }

            @Override
            public void onWaitingForReceipt(String s) {
                Log.e("发送逻辑中", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("发送逻辑失败", s);
            }
        });*/
    }

    /**
     * 连接成功后的第四步操作，(若该手机号码与该北斗卡号已经绑定，可跳过)
     * 设置H3的用户id
     */
    private void setID_H3(final String phoneNumber){
        HailiaoManager.getHailiaoManager().setUserIdAndServerNumber(phoneNumber, null, new HlSetUserIdCallBack() {
            @Override
            public void onSuccess(String s) {
                Log.e("设置id成功", s);
                Log.e("servercard", MainApp.getInstance().getServerCardNumber());
                if ("00000000000".equals(phoneNumber)){
                    //若为重新绑定的流程，则应在清零终端的手机号码成功后，立即去重新绑定手机号码，网络绑定或北斗绑定都可以
                    bindByNet();
                    //bindByBeidou();
                }else {
                    //连接流程已结束，可以发送短报文消息了
                }
//                getMachineInfo();
            }

            @Override
            public void onFailed(String s) {
                Log.e("设置id失败", s);
            }
        });
    }

    /**
     * 设置h3轨迹记录参数
     * @param freq  频度（秒为单位）
     * @param startTrail 是否开启轨迹记录
     */
    public void setTrailParams(int freq, boolean startTrail){
        HailiaoManager.getHailiaoManager().setTrailParams(freq, startTrail, new HlSetTrailParamsCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("设置轨迹记录参数成功", s);
                setLocationUpload(60);
            }

            @Override
            public void onFailed(String s) {
                Log.e("设置轨迹记录参数失败", s);
            }
        });
    }

    /**
     * 设置h3位置上报参数
     * @param freq  上报频度（以秒为单位）
     */
    public void setLocationUpload(int freq){
        HailiaoManager.getHailiaoManager().setLocationUploadParams(freq, new HlSetLocationUploadParamsCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("设置位置上报参数成功", s);
                getLocationUploadParams();
            }

            @Override
            public void onFailed(String s) {
                Log.e("设置位置上报参数失败", s);
            }
        });
    }

    /**
     * 读取位置上报参数
     */
    public void getLocationUploadParams(){
        HailiaoManager.getHailiaoManager().getLocationUploadParams(new HlGetLoactionUploadParamsCallback() {
            @Override
            public void onSuccess(String s, boolean b) {
                Log.e("读取位置上报参数成功", s + b);
                startLocationUpload();
            }

            @Override
            public void onFailed(String s) {
                Log.e("读取位置上报参数失败", s);

            }
        });
    }

    /**
     * 开启h3的位置上报
     */
    public void startLocationUpload(){
        HailiaoManager.getHailiaoManager().startLocationUpload(new HlStartLocationUploadCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("开启位置上报成功", s);
                stopLocationUpload();
            }

            @Override
            public void onFailed(String s) {
                Log.e("开启位置上报失败", s);
            }
        });
    }

    /**
     * 停止h3的位置上报
     */
    public void stopLocationUpload(){
        HailiaoManager.getHailiaoManager().stopLocationUpload(new HlStopLocationUploadCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("停止位置上报成功", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("停止位置上报失败", s);
            }
        });
    }

    /**
     * h3的语音开关
     * @param isSetMode  真-设置模式（open参数生效）/假-检查模式（open参数无效）
     * @param open  真-开启语音/假-关闭语音
     */
    public void setSoundSwitch(boolean isSetMode, boolean open){
        HailiaoManager.getHailiaoManager().setSoundSwitch(isSetMode, open, new HlSetSoundSwitchCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("设置声音成功", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("设置声音失败", s);
            }
        });
    }

    /**
     * 读取轨迹存储空间信息
     */
    public void getTrailCache(){
        hailiaoManager.getTrailCache(new HlGetTrailCacheCallback() {
            @Override
            public void onTrailCacheGet(TrailCacheDto trailCacheDto) {
                Log.e("读取轨迹存储空间信息成功：", "点数"+trailCacheDto.getTrailAccounts());
                Log.e("读取轨迹存储空间信息成功：", "条数"+trailCacheDto.getTrailCatalogAccounts());
                Log.e("读取轨迹存储空间信息成功：", "打点频度"+trailCacheDto.getTrailFreq());
                getTrailCatalog("000");
            }

            @Override
            public void onFailed(String s) {

            }
        });
    }

    /**
     * 读取H3指定id的轨迹目录信息。
     * @param trailNumber  轨迹段id（传入000则为读取所有目录）
     */
    public void getTrailCatalog(String trailNumber){
        hailiaoManager.getTrailCatalog(trailNumber, new HlGetTrailCatalogCallback() {
            @Override
            public void onTrailCatalogGet(TrailCatalogDto trailCatalogDto) {
                Log.e("读取轨迹目录信息成功：", "轨迹段id"+trailCatalogDto.getTrailId());
                Log.e("读取轨迹目录信息成功：", "轨迹段所属用户id"+trailCatalogDto.getOwnerPhone());
                Log.e("读取轨迹目录信息成功：", "轨迹段开始时间"+trailCatalogDto.getTrailStartTime());//（如“161117135900”则表示2016-11-17-13-59-00）
                Log.e("读取轨迹目录信息成功：", "轨迹段结束时间"+trailCatalogDto.getTraiEndTime());
                Log.e("读取轨迹目录信息成功：", "轨迹点数"+trailCatalogDto.getTrailAccounts());
                getTrail(trailCatalogDto.getTrailId(), trailCatalogDto.getTrailStartTime(), trailCatalogDto.getTraiEndTime());
            }

            @Override
            public void onFailed(String s) {

            }
        });
    }

    /**
     * 读取指定轨迹段的轨迹点信息
     * @param trailId  轨迹段id
     * @param trailStartTime  轨迹段的起始时间（读取轨迹目录信息接口可获取相关信息，格式如“161117135900”则表示2016-11-17-13-59-00）
     * @param trailEndTime  轨迹段的结束时间
     */
    public void getTrail(String trailId, String trailStartTime, String trailEndTime){
        hailiaoManager.getTrail(trailId, trailStartTime, trailEndTime, new HlGetTrailCallback() {
            @Override
            public void onTrailLocationReceivedOver(String s) {
                Log.e("读取指定轨迹段的轨迹点结束：", s);
            }

            @Override
            public void onTrailLocationGet(CardLocationDto cardLocationDto) {
                Log.e("读取指定轨迹段的轨迹点信息成功：", "经度"+cardLocationDto.getLatitude());
                Log.e("读取指定轨迹段的轨迹点信息成功：", "纬度"+cardLocationDto.getLongitude());
                Log.e("读取指定轨迹段的轨迹点信息成功：", "时间"+cardLocationDto.getTimeHex());//（如“161117135900”则表示2016-11-17-13-59-00）
                Log.e("读取指定轨迹段的轨迹点信息成功：", "速度"+cardLocationDto.getSpeed());
                Log.e("读取指定轨迹段的轨迹点信息成功：", "方向"+cardLocationDto.getDirection());
                Log.e("读取指定轨迹段的轨迹点信息成功：", "高程"+cardLocationDto.getAltitude());
            }

            @Override
            public void onFailed(String s) {
                Log.e("读取指定轨迹段的轨迹点失败：", s);
            }
        });
    }

    /**
     * 清空轨迹存储空间
     */
    public void clearTrail(){
        hailiaoManager.clearTrail(new HlClearTrailCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("清除成功：", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("清除失败：", s);
            }
        });
    }

    /**
     * 获取gps定位信息
     * @param freq 定位信息读取频度（以秒为单位，0表示单次读取并关闭）
     */
    private void getLocation(int freq){
        HailiaoManager.getHailiaoManager().getLocationInfo(freq, new HlGetLocationCallBack() {

            @Override
            public void onGpsLocationGet(CardLocationDto cardLocationDto) {
                Log.e("读取位置成功", cardLocationDto.getAltitude() + "");
                Log.e("读取位置成功", cardLocationDto.getLatitude() + "");
                Log.e("读取位置成功", cardLocationDto.getLongitude() + "");
                Log.e("读取位置成功", cardLocationDto.getTimeHex() + "");

            }

            @Override
            public void onGpsSatelliteInfoGet(GpsSatelliteDto gpsSatelliteDto) {
                Log.e("读取位置成功", gpsSatelliteDto.getAllSatelliteNumber() + "");
                Log.e("读取位置成功", gpsSatelliteDto.getWeakSnrSatelliteNumber() + "");
                Log.e("读取位置成功", gpsSatelliteDto.getBestSnrallSatelliteNumber() + "");

            }

            @Override
            public void onFailed(String s) {
                Log.e("读取位置失败", s);
            }
        });
    }

    /**
     * 查询/设置rd模块的开启和关闭状态
     * @param isSet true-设置rd模块状态（true则open参数生效）； false-查询rd模块状态（false则open参数无效）
     * @param open  true-设置rd模块开启；false-rd设置模块关闭
     */
    private void rdStatus(boolean isSet, boolean open){
        hailiaoManager.setRdOpen(isSet, open, new HlRdStatusCallback() {
            @Override
            public void onSuccess(boolean b) {
                Log.e("当前rd模块状态是否为开启", b +"");
            }

            @Override
            public void onFailed(String s) {
                Log.e("读取/设置操作失败",s);
            }
        });
    }


    /**
     * 发送透传自定义短报文
     */
    public void sendCustomMsg(){
       /* hailiaoManager.sendCustomMsg("0242265", new byte[]{0x00,0x00,0x13,0x00}, new HlSendCustomCallBack() {
            @Override
            public void onSuccess(String s) {
                Log.e("成功", s);
            }

            @Override
            public void onFailed(String s) {
                Log.e("失败", s);
            }
        });*/
    }


    /**
     * 注册接口
     */
    private void register(){
        /*hailiaoManager.submitInfo("黄莹", "431121198708121751", "18670339700", new HlSendSubmitCallBack() {
            @Override
            public void onSubmitSuccess(String s) {
                Log.e("注册成功：", s);
            }

            @Override
            public void onSubmitFailed(String s) {
                Log.e("注册失败：", s);
            }
        });*/
    }



    HlSendMessageInterface hlSendMessageInterface = new HlSendMessageInterface() {
        //发送成功
        @Override
        public void onMessageSendSuccess(String message) {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

        }
        //发送失败
        @Override
        public void onMessageSendFailed(String message) {
            Toast.makeText(getApplicationContext(), "失败，请重试" , Toast.LENGTH_SHORT).show();

        }
    };

    HlMessageReceiveInterface hlMessageReceiveInterface = new HlMessageReceiveInterface() {
        @Override
        public void onReceiveMessageSuccess(String message) {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onReceiveMessageFailed(String message) {
            Toast.makeText(getApplicationContext(), "失败，请重试", Toast.LENGTH_SHORT).show();

        }
    };

    public static boolean isOpenNetwork(Context context) {
        try {
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            return connManager.getActiveNetworkInfo() != null && connManager.getActiveNetworkInfo().isAvailable();
        }catch (Exception e){
            Log.e("错误", e.getMessage());
        }
        return false;
    }





    /*************************************************下面的代码可删除*********************************************/
    private void roundCheckMessage(){
        new Thread(){
            @Override
            public void run() {
                while (true){
//                    checkBdMessage();
                    HailiaoMessageUtil.getInstance().checkBdMessage("237448", "0", hlMessageReceiveInterface);
                    try{
                        sleep(5000);
                    }catch (Exception e){
                        Log.e("出现错误", e.getMessage());
                    }
                }
            }
        }.start();

    }

    private void checkBdMessage(){
        if (isOpenNetwork(this)) {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
//                    return HailiaoMessageUtil.getInstance().mCheckBdMessage("237448");
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    if (s == null){
                        Toast.makeText(getApplicationContext(), "失败，请重试", Toast.LENGTH_SHORT).show();
                    }else {
                        try{
                            JSONObject jsonObject = new JSONObject(s);
                            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                        }catch (Exception e){

                        }
                    }
                }
            }.execute((Void) null);

        }else {
            Toast.makeText(this, "请先开启网络", Toast.LENGTH_SHORT).show();
        }
    }

}
